#pragma once
#include<iostream>
#include"Socket.hpp"
#include"Connection.hpp"
#include"Reactor.hpp"
static const int buffersize =512;
//处理IO具体方法集
class HandlerConnection
{
public:
    HandlerConnection(handler_t process):_process(process)
    {};
    void HandlerRecver(Connection* con)
    {
        char buffer[buffersize];
        while(true)
        {
            errno =0;
            int n =recv(con->Sockfd(),buffer,sizeof(buffer)-1,0);
            if(n>0)
            {
                buffer[n] =0;
                con->AddInBuffer(buffer);
            }
            else
            {
                if(errno==EWOULDBLOCK)
                break;
                else if(errno==EINTR)
                continue;
                else
                {
                    con->_handler_excepter(con);
                    return;
                }
            }
        }
         _process(con);
    }
    void HandlerSender(Connection* con)
    {
        while(true)
        {
            errno =0;
            int n =send(con->Sockfd(),con->OutBuffer().c_str(),con->OutBuffer().size(),0);
            if(n>0)
                con->DelOutbuffer(n);
            else if(n==0)//数据发送完毕或者用户退出
                break;
            else
            {
                if(errno ==EWOULDBLOCK)
                break;
                else if(errno==EINTR)
                continue;
                else
                {
                    con->_handler_excepter(con);
                    return;
                }
            }
        }
        if(!con->OutBuffer().empty())//缓冲区满了
        con->_R->EnableConnectionReadWrite(con->Sockfd(),true,true);
        else
        con->_R->EnableConnectionReadWrite(con->Sockfd(),true,false);
    }
    void HandlerExcepter(Connection* con)
    {
        LOG(DEBUG,"%d:del\n",con->Sockfd());
        con->_R->DelConnection(con->Sockfd());
    }
private:
    handler_t _process;
};